import pandas as pd
from flask import send_file
from io import BytesIO

def export_sales_data_optimized(df, manufacturers, year_range):
    """
    导出销售数据（优化版）
    参数: df - 预加载的销售数据DataFrame
    """
    try:
        # 根据参数筛选数据
        filtered_df = df.copy()
        
        if manufacturers and manufacturers != ['all']:
            filtered_df = filtered_df[filtered_df['厂商'].isin(manufacturers)]
        
        if year_range and year_range != 'all':
            # 解析年份范围，例如 "2020-2023"
            if '-' in year_range:
                start_year, end_year = map(int, year_range.split('-'))
                filtered_df = filtered_df[
                    (filtered_df['年份'] >= start_year) & 
                    (filtered_df['年份'] <= end_year)
                ]
            else:
                filtered_df = filtered_df[filtered_df['年份'] == int(year_range)]
        
        # 创建Excel文件
        output = BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            filtered_df.to_excel(writer, sheet_name='销售数据', index=False)
        
        output.seek(0)
        
        return send_file(
            output,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=f'汽车销售数据_{year_range}.xlsx'
        )
        
    except Exception as e:
        return {
            'success': False,
            'error': f'导出数据失败: {str(e)}'
        }